<?php
/**
 * 会员商城
 *
 * 
 *
 *
 * @copyright  Copyright (c) 2007-2013 ShopNC Inc. (http://www.shopnc.net)
 * @license    http://www.shopnc.net
 * @link       http://www.shopnc.net
 * @since      File available since Release v1.1
 */
defined('InShopNC') or exit('Access Invalid!');

class show_storeControl extends MobileControl {
	private $templatestate_arr;
	
	public function __construct(){
		parent::__construct();
	}
	public function indexOp(){
		$goods_class =new goodsModel();
		//获得商城ID
		$store_id = intval($_GET['id']);
		if ($store_id <= 0){
			mobileJump('您要查看的商城不存在或正在被审核中');
		}
		//检查商城状态
		$store_info = $this->getStoreInfo($store_id);
		
		$model = Model();
		//开启代金券功能后查询代金券相应信息
		if (C('voucher_allow') == 1){
			//查询已兑换代金券券数量
			$vouchercount = 0;
			if($_SESSION['is_login'] == '1'){
				$vouchercount = $model->table('voucher')->where(array('voucher_owner_id'=>$_SESSION['member_id'],'voucher_state'=>$this->voucherstate_arr['unused'][0]))->count();
			}
			Tpl::output('vouchercount',$vouchercount);
			//查询代金券面额
			$pricelist =  $model->table('voucher_price')->order('voucher_price asc')->select();
			Tpl::output('pricelist',$pricelist);
			//查询代金券列表
			$field = 'voucher_template.*,store.store_id,store.store_label,store.store_name,store.store_domain';
			$on = 'voucher_template.voucher_t_store_id=store.store_id';
			$new_voucher = $model->table('voucher_template,store')->field($field)->join('left')->on($on)->where(array('voucher_t_state'=>$this->templatestate_arr['usable'][0],'voucher_t_end_date'=>array('gt',time()),'voucher_t_store_id'=>(int)$_GET['id']))->limit(16)->select();
			if (!empty($new_voucher)){
				foreach ($new_voucher as $k=>$v){
					if (!empty($v['voucher_t_customimg'])){
						$v['voucher_t_customimg'] = SiteUrl.DS.ATTACH_VOUCHER.DS.$v['voucher_t_store_id'].DS.$v['voucher_t_customimg']."_small.".get_image_type($v['voucher_t_customimg']);
					}else{
						$v['voucher_t_customimg'] = defaultGoodsImage('small');
					}
					if (!empty($v['store_label'])){
						$v['store_label'] = SiteUrl.DS.ATTACH_STORE.DS.$v['store_label'];
					}
					$v['voucher_t_limit'] = intval($v['voucher_t_limit']);
					$new_voucher[$k] = $v;
				}
			}
			Tpl::output('new_voucher',$new_voucher);	
		}
		
		$page	= new Page();
        $page->setEachNum(40);
		$page->setStyle('admin');
		
		$conditionArr = array();
		$conditionArr['store_id']		= $store_info['store_id'];
		$conditionArr['goods_state']	= 0;
		$conditionArr['goods_show']		= 1;
		$conditionArr['keyword']		= trim($_GET['keyword']);
		$conditionArr['start_price']	= floatval($_GET['start_price']);
		$conditionArr['end_price']		= floatval($_GET['end_price']);
		if(trim($_GET['order'] != 'asc'))$_GET['order']	= 'desc';
		// 排序
		switch (trim($_GET['key'])){
			case 'price':
				$conditionArr['order'] = 'goods.goods_store_price '.$_GET['order'];
				break;
			case 'sale':
				$conditionArr['order'] = 'goods.salenum '.$_GET['order'];
				break;
			case 'click':
				$conditionArr['order'] = 'goods.goods_click '.$_GET['order'];
				break;
			case 'collect':
				$conditionArr['order'] = 'goods.goods_collect '.$_GET['order'];
				break;
			case 'new':
				$conditionArr['order'] = 'goods.goods_starttime '.$_GET['order'];
				break;
			default:
				$conditionArr['order'] = 'goods.goods_starttime desc';
				break;
		}
		//根据买家用户信息所在地区展示在相应地区展示的商品-市级-省级
		if(isset($_SESSION['is_login']) && (int)$_SESSION['is_login'] == 1){
			$member = Model('member')->infoMember(array('member_id'=>(int)$_SESSION['member_id']));
			$area_info = preg_split('/\t/', $member['member_areainfo'],-1,PREG_SPLIT_NO_EMPTY);
			if(count($area_info)==1){
				$conditionArr['show_in_province_ids'] = (int)$member['member_provinceid'];
			}elseif(count($area_info)==2 || count($area_info)==3){
				$conditionArr['show_in_city_ids'] = (int)$member['member_cityid'];
			}
		}
		//判断当前商城是否店主访问，是则清除区域展示限制
		if($member['store_id'] == $store_info['store_id']){
			unset($conditionArr['show_in_province_ids']);
			unset($conditionArr['show_in_city_ids']);
		}
		//查询分类下的子分类
		if ($_GET['stc_id']){
			$model_store_class =new my_goods_classModel();
			$stc_id_arr = $model_store_class->getChildAndSelfClass(intval($_GET['stc_id']),'1');
			if (is_array($stc_id_arr) && count($stc_id_arr)>0){
				$conditionArr['stc_id_in'] = implode(',',$stc_id_arr);
			}else{
				$conditionArr['stc_id'] = $stc_id_arr;
			}
			$goods_list = $goods_class->getGoods($conditionArr,$page,'goods.*','stc');
		}else {
			$goods_list = $goods_class->getGoods($conditionArr,$page,'goods_id,goods_name,gc_id,goods_image,store_id,goods_store_price,group_price,xianshi_discount,group_flag,xianshi_flag','goods');
		}
		if (!empty($goods_list) && is_array($goods_list)){
			foreach ($goods_list as $key=>$value){
				// 格式化价格显示
				$goods_list[$key]['goods_price'] = ncPriceFormat($value['goods_price']);
			}
		}

		Tpl::output('goods_list',$goods_list);

		//幻灯片图片
		if($store_info['store_slide'] != '' && $store_info['store_slide'] != ',,,,' && false){
			$slideImg = array();
			$slideUrl = array();
			$slideArr = explode(',', $store_info['store_slide']);
			$urlArr = explode(',', $store_info['store_slide_url']);
			foreach($slideArr as $key=>$val){
				if(is_file(BasePath.DS.ATTACH_SLIDE.DS.$val)){
					$slideImg[] = $val;
					$slideUrl[] = $urlArr[$key];
				}
			}
			Tpl::output('store_slide', $slideImg);
			Tpl::output('store_slide_url',$slideUrl);
		}
		Tpl::output('page','index');
		
		//当前商城收藏会员ID
		$sql = "SELECT member_id FROM #__favorites WHERE fav_id = '$store_id' AND fav_type = 'store'";
		$rs = Db::queryAll($sql);
		$m_id = array();
		foreach($rs as $item){
			$m_id[] = $item['member_id'];
		}
		Tpl::output('m_id',$m_id);
		
		//取此商城所有商品的平均分
		 $sql ="SELECT goods_quality_scores,package_quality_scores,shipping_speed_scores,after_sale_scores FROM #__evaluate_order_goods WHERE ogeval_storeid=".$store_info['store_id'];
		 $this_store_goods_score =db::queryAll($sql);
		 if(!empty($this_store_goods_score)){
			$this_store_goods_avg_score =storeModel::array_avg($this_store_goods_score);
			$store_info['goods_quality_credit'] =ceil($this_store_goods_avg_score['goods_quality_scores']);
			$store_info['package_quality_credit'] =ceil($this_store_goods_avg_score['package_quality_scores']);
			$store_info['shipping_speed_credit'] =ceil($this_store_goods_avg_score['shipping_speed_scores']);
			$store_info['after_sale_credit'] =ceil($this_store_goods_avg_score['after_sale_scores']);
		 }
		
		//得到商城页面seo信息
		$seo_param = array();
		$seo_param['shopname'] = $store_info['store_name'];
		$seo_param['key']  = $store_info['store_keywords'];
		$seo_param['description'] = $store_info['store_description'];
		Model('seo')->type('shop')->param($seo_param)->show();
		Tpl::output('store_info',$store_info);
		$this->_assignMobileData($page);
		Tpl::showpage('store.index');
	}
    /**
     * ajax 商城首页收藏商城
     */
    public function ajax_fav_storeOp(){
        $store_id = intval($_POST['store_id']);
        if($store_id<=0){
            echo json_encode(array('state'=>false,'msg'=>'商城不存在'));exit;
        }
        $sql = "select * from #__favorites where member_id='{$_SESSION['member_id']}' and fav_type='store' and fav_id='$store_id'";
        $row = Db::queryRow($sql);
        if(is_array($row) && !empty($row)){
            echo json_encode(array('state'=>false,'msg'=>'你已经收藏过'));exit;
        }
        $insert_array = array();
        $insert_array['fav_type'] = 'store';
        $insert_array['fav_id'] = $store_id;
        $insert_array['member_id'] = $_SESSION['member_id'];
        $insert_array['fav_time'] = time();
        if(!Db::insert('favorites',$insert_array)){
            echo json_encode(array('state'=>false,'msg'=>'系统繁忙，请稍候'));
            exit;
        }
        echo json_encode(array('state'=>true,'msg'=>'收藏成功'));
        /*收藏成功，则更新商城的收藏数量*/
        $sql = "update #__store set store_collect=store_collect+1 where store_id='$store_id'";
        Db::execCommand($sql);
    }

	/**
	 * ajax 商城流量统计入库
	 */
	public function ajax_flowstat_recordOp(){
		if($_GET['id'] != '' && $_SESSION['store_id'] != $_GET['id']){
			//确定统计分表名称
			$flow_tableid = 0;
			$len = strlen(strval(intval($_GET['id'])));
			$last_num = substr(strval(intval($_GET['id'])), $len-1,1);
			switch ($last_num){
				case 1:
					$flow_tableid = 1;
					break;
				case 2:
					$flow_tableid = 1;
					break;
				case 3:
					$flow_tableid = 2;
					break;
				case 4:
					$flow_tableid = 2;
					break;
				case 5:
					$flow_tableid = 3;
					break;
				case 6:
					$flow_tableid = 3;
					break;
				case 7:
					$flow_tableid = 4;
					break;
				case 8:
					$flow_tableid = 4;
					break;
				case 9:
					$flow_tableid = 5;
					break;
				case 0:
					$flow_tableid = 5;
					break;
			}
			$flow_tablename = 'flowstat_'.$flow_tableid; 
			//判断是否存在当日数据信息
			$date = date('Ymd',time());
			$model = Model();
			$stat_model =new statisticsModel();
			if($_GET['act_param'] == 'show_store' && ($_GET['op_param'] == 'index' || $_GET['op_param'] == 'credit' || $_GET['op_param'] == 'store_info')){
				$flow_date_array = $model->table($flow_tablename)->where(array('date'=>$date,'store_id'=>intval($_GET['id'])))->find();
			}else if($_GET['act_param'] == 'goods' && $_GET['op_param'] == 'index'){
				$flow_date_array = $model->table($flow_tablename)->where(array('date'=>$date,'goods_id'=>intval($_GET['goods_id'])))->find();
				$flow_date_array_sub = $model->table($flow_tablename)->where(array('date'=>$date,'store_id'=>intval($_GET['id'])))->find();
			}
			//向数据库写入访问量数据
			$update_param = array();
			$update_param['table'] = $flow_tablename;
			$update_param['field'] = 'clicknum';
			$update_param['value'] = 1;
			if(is_array($flow_date_array) && !empty($flow_date_array)){//已经存在数据则更新
				if($_GET['act_param'] == 'show_store' && ($_GET['op_param'] == 'index' || $_GET['op_param'] == 'credit' || $_GET['op_param'] == 'store_info')){
					$update_param['where'] = "WHERE date = '".$date."' AND store_id = '".intval($_GET['id'])."' AND goods_id = '0'";
					$stat_model->updatestat($update_param);
				}else if($_GET['act_param'] == 'goods' && $_GET['op_param'] == 'index'){
					$update_param['where'] = "WHERE date = '".$date."' AND goods_id = '".intval($_GET['goods_id'])."'";
					$stat_model->updatestat($update_param);
					$update_param['where'] = "WHERE date = '".$date."' AND store_id = '".intval($_GET['id'])."' AND goods_id = '0'";
					$stat_model->updatestat($update_param);
				}
			}else{//未存在数据则插入一行访问量数据
				if($_GET['act_param'] == 'show_store' && ($_GET['op_param'] == 'index' || $_GET['op_param'] == 'credit' || $_GET['op_param'] == 'store_info')){
					$model->table($flow_tablename)->insert(array('date'=>$date,'clicknum'=>1,'store_id'=>intval($_GET['id']),'type'=>'sum','goods_id'=>0));
				}else if($_GET['act_param'] == 'goods' && $_GET['op_param'] == 'index'){
					if(is_array($flow_date_array_sub) && !empty($flow_date_array_sub)){//已经有商城数据则只插入一行并更新商城访问数据
						$model->table($flow_tablename)->insert(array('date'=>$date,'clicknum'=>1,'store_id'=>intval($_GET['id']),'type'=>'goods','goods_id'=>intval($_GET['goods_id'])));
						$update_param['where'] = "WHERE date = '".$date."' AND store_id = '".intval($_GET['id'])."' AND goods_id = '0'";
						$stat_model->updatestat($update_param);
					}else{//没有商城访问数据的则建立两行访问数据
						$model->table($flow_tablename)->insert(array('date'=>$date,'clicknum'=>1,'store_id'=>intval($_GET['id']),'type'=>'sum','goods_id'=>0));
						$model->table($flow_tablename)->insert(array('date'=>$date,'clicknum'=>1,'store_id'=>intval($_GET['id']),'type'=>'goods','goods_id'=>intval($_GET['goods_id'])));
					}
				}
			}
		}
		echo json_encode(array('done'=>true,'msg'=>'done'));
	}
}
?>
